<template>
  <el-dialog v-model="dialogVisible" :title="'找回密码'" width="30%">
    <!-- 步骤条 -->
    <div style="margin-bottom: 30px;">
      <el-steps :active="step - 1" finish-status="success">
        <el-step title="验证手机号" />
        <el-step title="校验验证码" />
        <el-step title="修改密码" />
        <el-step title="完成" />
      </el-steps>
    </div>

    <!-- 第一步：验证手机号 -->
    <el-form v-if="step === 1" :model="userForm" ref="formRef1" :rules="rules1" label-width="120px">
      <el-form-item label="账号" prop="account">
        <el-input v-model="userForm.account" placeholder="请输入账号" style="width: 240px" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userForm.phone" placeholder="请输入手机号" style="width: 240px" />
      </el-form-item>
    </el-form>

    <!-- 第二步：校验验证码 -->
    <el-form v-if="step === 2" :model="userForm" ref="formRef2" :rules="rules2" label-width="120px">
      <el-form-item label="验证码" prop="captcha">
        <el-input v-model="userForm.captcha" placeholder="请输入验证码" style="width: 140px; margin-right: 10px;" />
        <el-button :disabled="isCounting" @click="sendVerificationCode">
          {{ isCounting ? `${countdown}秒后重发` : '发送验证码' }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 第三步：修改密码 -->
    <el-form v-if="step === 3" :model="userForm" ref="formRef3" :rules="rules3" label-width="120px">
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="userForm.newPassword" type="newPassword" placeholder="请输入新密码" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="userForm.confirmPassword" type="password" placeholder="请输入确认密码" show-password />
      </el-form-item>
    </el-form>

    <!-- 第四步：完成 -->
    <div v-if="step === 4">
      <h3>密码修改成功！</h3>
      <p>您可以使用新密码登录。</p>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="step === 1" type="primary" @click="validateAccountAndPhone">下一步</el-button>
        <el-button v-if="step === 2" type="primary" @click="validateCaptcha">下一步</el-button>
        <el-button v-if="step === 3" type="primary" @click="onSubmit">提交</el-button>
        <el-button v-if="step === 4" type="primary" @click="doLogin">登录</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/userStore'
import { sendSms } from "@/apis/common.js";
import { validateAccountAndPhoneAPI, checkCaptchaAPI, resetPasswordAPI } from '@/apis/user.js';

const userStore = useUserStore()
const router = useRouter()

// 状态和引用定义
const dialogVisible = ref(false);
const step = ref(1);
const formRef1 = ref(null);
const formRef2 = ref(null);
const formRef3 = ref(null);
const userForm = ref({
  account: '',
  phone: '',
  captcha: '',
  newPassword: '',
  confirmPassword: '',
});

const isCounting = ref(false);
const countdown = ref(60);

// 表单验证规则
const rules1 = {
  account: [{ required: true, message: '账号不能为空', trigger: 'blur' },
  { min: 5, max: 20, message: "账号为5-20个字符", trigger: "blur" },
  {
    pattern: /^[a-zA-Z0-9_]+$/,
    message: '账号只能包含字母、数字和下划线',
    trigger: 'blur'
  },
  ],
  phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' },
  {
    pattern: /^1[3-9]\d{9}$/,
    message: "请输入有效的手机号码",
    trigger: "blur",
  }
  ],
};

const rules2 = {
  captcha: [{ required: true, message: '验证码不能为空', trigger: 'blur' },
  {
    pattern: /^\d{6}$/,
    message: "验证码必须是6位数字",
    trigger: "blur"
  },
  ],
};

const rules3 = {
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 14, message: "新密码为6-14个字符", trigger: "blur" },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).{6,}$/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    },
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { min: 6, max: 14, message: '确认密码长度为6-14个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

const validateAccountAndPhone = async () => {
  await formRef1.value.validate();
  const res = await validateAccountAndPhoneAPI(userForm.value.account, userForm.value.phone);
  if (res.code == 1) {
    step.value = 2;
  }
};

// 发送验证码的逻辑
const sendVerificationCode = async () => {
  if (!userForm.value.phone) {
    ElMessage.error("请先输入手机号");
    return;
  }

  isCounting.value = true;
  countdown.value = 60;

  try {
    const res = await sendSms(userForm.value.phone);
    if (res.code == 1) {
      ElMessage.success("验证码已发送");
    } else {
      ElMessage.error("发送失败，请稍后重试");
    }

    // 启动倒计时
    const timer = setInterval(() => {
      if (countdown.value <= 0) {
        clearInterval(timer);
        isCounting.value = false;
      } else {
        countdown.value--;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error("发送失败，请稍后重试");
    isCounting.value = false;
  }
};

const validateCaptcha = async () => {
  await formRef2.value.validate();
  const res = await checkCaptchaAPI(userForm.value.phone, userForm.value.captcha);
  if (res.code == 1) {
    step.value = 3;
  }
};

// 提交表单，重置密码
const onSubmit = async () => {
  await formRef3.value.validate();
  const passwordResetForm = {
    account: userForm.value.account,
    newPassword: userForm.value.newPassword,
    confirmPassword: userForm.value.confirmPassword,
  };
  const res = await resetPasswordAPI(passwordResetForm);
  if (res.code == 1) {
    step.value = 4;
  }
};

const doLogin = async () => {
      const account = userForm.value.account;
      const password = userForm.value.newPassword;
      await userStore.getUserInfo({ account, password });
      ElMessage.success("登录成功");
      router.replace({ path: '/' });
}

// 打开对话框并初始化数据
const open = () => {
  dialogVisible.value = true;
  userForm.value = {};
};

// 暴露方法
defineExpose({
  open,
});
</script>
